package com.swallow.auth.infrastructure.acl.oauth2.handler;

import com.swallow.auth.common.result.R;
import com.swallow.auth.common.result.Result;
import com.swallow.auth.common.utils.GsonUtil;
import com.swallow.auth.infrastructure.mysql.po.AccountPO;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 18310740596@163.com
 * @since: 2024-05-14 14:58:02
 * @version: v1.0.0
 * @describe:
 */
public class SuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Map<String, Object> content = new HashMap<>();

        Result<Object> success = R.success();
        if (authentication instanceof OAuth2AccessTokenAuthenticationToken authenticationToken) {
            content.put("access_token", authenticationToken.getAccessToken().getTokenValue());
            content.put("refresh_token", Objects.requireNonNull(authenticationToken.getRefreshToken()).getTokenValue());
            content.put("scope", String.join(",", authenticationToken.getAccessToken().getScopes()));
            content.put("token_type", authenticationToken.getAccessToken().getTokenType().getValue());

            long issueAt = Objects.requireNonNull(authenticationToken.getAccessToken().getIssuedAt()).toEpochMilli();
            long expiresAt = Objects.requireNonNull(authenticationToken.getAccessToken().getExpiresAt()).toEpochMilli();
            content.put("expires_in", (expiresAt - issueAt) / 1000);

            success.setData(content);
        } else if (authentication.getPrincipal() instanceof AccountPO account){

            success.setData(account.getAccountNo());
        }

        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(GsonUtil.toJson(success));
        response.getWriter().flush();
    }
}
